package com.example.innospace.demos.web.controller;


import com.example.innospace.demos.pojo.dto.*;
import com.example.innospace.demos.pojo.entity.Admin;
import com.example.innospace.demos.pojo.entity.Student;
import com.example.innospace.demos.pojo.entity.Teacher;
import com.example.innospace.demos.pojo.enums.MessageEnum;
import com.example.innospace.demos.pojo.enums.ResponseCodeEnum;
import com.example.innospace.demos.pojo.result.PageResult;
import com.example.innospace.demos.pojo.result.R;
import com.example.innospace.demos.pojo.vo.AdminVO;
import com.example.innospace.demos.pojo.vo.TeacherVO;
import com.example.innospace.demos.utils.JWTUtils;
import com.example.innospace.demos.utils.OssUtil;
import com.example.innospace.demos.web.service.AdminService;
import com.example.innospace.demos.web.service.ProjectService;
import com.example.innospace.demos.web.service.StudentService;
import com.example.innospace.demos.web.service.TeacherService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员端
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private OssUtil ossUtil;
    @Autowired
    private AdminService adminService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private ProjectService projectService;
    /**
     * 管理员登录
     * @param
     * @return
     */
    @PostMapping("/login")
    public R login(HttpServletRequest request, @RequestBody Admin admin)
    {
        Admin admin1=adminService.findById(admin.getAdminId());
        //查询用户
        if(admin1==null)
        {
            return R.error(ResponseCodeEnum.NOT_FOUND, MessageEnum.USER_NOT_EXIST);
        }
        //查询到了
        //判断密码是否正确
        //loginUser对象中的password是密文
        if(admin1.getPassword().equals(admin.getPassword())) {
            //登录成功
            request.getSession().setAttribute("adminId", admin.getAdminId());
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", admin.getAdminId());
            claims.put("username", admin.getName());
            //登录成功以后，从登录用户中获得id，获得用户名字，通过JwtUtil来获得这样一个（用户）字段下的Token令牌
            String token = JWTUtils.genToken(claims);
            return R.success(ResponseCodeEnum.SUCCESS,token,MessageEnum.LOGIN_SUCCESS);//将令牌传出
        }
        return R.error(ResponseCodeEnum.BAD_REQUEST,MessageEnum.PASSWORD_ERROR);
    }




    /**
     * 退出登录
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        //1.清除session中的用户id
        request.getSession().removeAttribute("adminId");
        //2.返回结果
        return R.success(ResponseCodeEnum.SUCCESS,MessageEnum.LOGOUT_SUCCESS);
        //3.页面会跳转回登录界面
    }

    /**
     * 管理员信息回显
     * @param adminId 管理员的账号
     * @return
     */
    @GetMapping("/admin/info")
    public R<AdminVO> getAdminInfo(@RequestParam String adminId)
    {
        if (adminId == null || adminId.isEmpty()) {
            return R.error(ResponseCodeEnum.BAD_REQUEST, MessageEnum.PARAMETER_INVALID);
        }
        AdminVO adminVO=new AdminVO();
         Admin admin=adminService.findById(adminId);
         if(admin==null)
             return R.error(ResponseCodeEnum.BAD_REQUEST,MessageEnum.USER_NOT_EXIST);
        BeanUtils.copyProperties(admin,adminVO);
        return R.success(ResponseCodeEnum.SUCCESS,adminVO,MessageEnum.OPERATION_SUCCESS);
    }


    /**
     * 修改管理员信息
     * @param admin 管理员信息
     * @return
     */
    @PutMapping("/admin/update")
    public R<String> updateAdminInfo(@RequestBody Admin admin )
    {
        String msg=adminService.updateAminInfo(admin);
        return R.success(ResponseCodeEnum.SUCCESS,MessageEnum.OPERATION_SUCCESS);
    }




    /**
     * 上传头像
     * @param adminId
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/admin/uploadAvatar")
    public R<String> upload(@RequestParam String adminId,@RequestParam("file") MultipartFile file) throws IOException {
        String fileUrl = ossUtil.uploadFile(file);

        // 将文件 URL 存储到数据库（这里需要调用 Service 层）
        adminService.updateAvatar(adminId, fileUrl);

        return R.success(ResponseCodeEnum.SUCCESS,fileUrl,MessageEnum.UPLOAD_SUCCESS);
    }


    /**
     * 下载头像
     * @param adminId
     * @return
     */
    @GetMapping("/admin/getAvatar")
    public R<String> getAvatar(@RequestParam String adminId) {
        // 从数据库获取头像文件的 URL（这里需要调用 Service 层）
        String fileUrl =adminService.getAvatar(adminId);

        // 返回文件的 URL
        return R.success(ResponseCodeEnum.SUCCESS,fileUrl,MessageEnum.OPERATION_SUCCESS);
    }
    /**
     * 添加学生用户
     * @param studentDTO
     * @return
     */
    @PostMapping("/student/add")
    public R addStudent(@RequestBody StudentDTO studentDTO)
    {
        Student student=studentService.findById(studentDTO.getStudentId());
        if(student!=null)
            return R.error(ResponseCodeEnum.BAD_REQUEST, MessageEnum.DATA_ALREADY_EXISTS);
        studentService.insert(studentDTO);
        return R.success(ResponseCodeEnum.SUCCESS,MessageEnum.OPERATION_SUCCESS);
    }

    /**
     * 添加老师用户
     * @param teacherDTO
     * @return
     */
    @PostMapping("/teacher/add")
    public R addTeacher(@RequestBody TeacherDTO teacherDTO)
    {
        Teacher teacher=teacherService.findById(teacherDTO.getTeacherId());
        if(teacher!=null)
            return R.error(ResponseCodeEnum.BAD_REQUEST,MessageEnum.DATA_ALREADY_EXISTS);
        teacherService.insert(teacherDTO);
        return R.success(ResponseCodeEnum.SUCCESS,MessageEnum.OPERATION_SUCCESS);
    }

    /**
     * 添加管理员用户
     * @param adminDTO
     * @return
     */
    @PostMapping("/admin/add")
    public R addAdmin(@RequestBody AdminDTO adminDTO)
    {
        Admin admin=adminService.findById(adminDTO.getAdminId());
        if(admin!=null)
            return R.error(ResponseCodeEnum.BAD_REQUEST,MessageEnum.DATA_ALREADY_EXISTS);
        adminService.insert(adminDTO);
        return R.success(ResponseCodeEnum.SUCCESS,MessageEnum.OPERATION_SUCCESS);
    }

    /**
     * 批量删除管理员
    */
    @DeleteMapping("/admin/delete")
    public R batchDeleteAdmins(@RequestBody  List<String> adminIds) {
        if(adminIds.isEmpty())
            return R.error(ResponseCodeEnum.BAD_REQUEST,MessageEnum.PARAMETER_INVALID);

        if(adminService.batchDeleteById(adminIds))
        {
            return R.success(ResponseCodeEnum.SUCCESS,MessageEnum.OPERATION_SUCCESS);
        }
        return R.error(ResponseCodeEnum.BAD_REQUEST,MessageEnum.OPERATION_FAILED);




    }


    /**
     * 批量删除老师
     * @param
     * @return
     */
    //TODO 需要补充关于状态的判断
   @DeleteMapping("/teacher/delete")
    public R batchDeleteTeachers(@RequestBody List<String> teacherIds)
   {

       if(teacherIds.isEmpty())
           return R.error(ResponseCodeEnum.BAD_REQUEST,MessageEnum.PARAMETER_INVALID);
       if(teacherService.batchDeleteById(teacherIds))
       return R.success(ResponseCodeEnum.SUCCESS,MessageEnum.DELETE_SUCCESS);
       return R.error(ResponseCodeEnum.BAD_REQUEST,MessageEnum.DELETE_FAILED);
   }

    /**
     *  根据老师的id修改老师的信息
     * @param teacher
     * @return
     */
   @PutMapping("/teacher/update")
   public R updateTeacherInfo( @RequestBody Teacher teacher)
   {
       if(teacher==null)
           return R.error(ResponseCodeEnum.BAD_REQUEST,MessageEnum.PARAMETER_INVALID);
       teacherService.updateTeacherInfo(teacher.getTeacherId(),teacher);
       return R.success(ResponseCodeEnum.SUCCESS,MessageEnum.SAVE_SUCCESS);
   }

    /**
     * 老师账号的密码重置
     * @param teacherId
     * @return
     */
    @PutMapping("/teacher/resetpassword")
    public R resetTeacherPassword(@RequestParam String teacherId)
    {
        teacherService.resetTeacherPassword(teacherId);
        return R.success(ResponseCodeEnum.SUCCESS,MessageEnum.OPERATION_SUCCESS);
    }

    /**
     * 老师账号信息回显
     * @param teacherId
     * @return
     */
    @GetMapping("/teacher/info")
    public R<TeacherVO> getTeacherInfo(@RequestParam String teacherId)
    {

        Teacher teacher=teacherService.findById(teacherId);
        TeacherVO teacherVO=new TeacherVO();
        BeanUtils.copyProperties(teacher,teacherVO);
        return R.success(ResponseCodeEnum.SUCCESS,teacherVO,MessageEnum.OPERATION_SUCCESS);
    }

    /**
     * 删除学生
     * @param
     * @return
     */
    @DeleteMapping("/student/delete")
    public R batchDeleteStudents(@RequestBody List<String> studentIds)
    {
        if(studentIds.isEmpty())
            return R.error(ResponseCodeEnum.BAD_REQUEST,MessageEnum.PARAMETER_INVALID);
        if(studentService.batchDeleteStudents(studentIds))
        return R.success(ResponseCodeEnum.SUCCESS,MessageEnum.OPERATION_SUCCESS);
        return R.error(ResponseCodeEnum.BAD_REQUEST,MessageEnum.DELETE_FAILED);
    }


    /**
     * 根据学生id修改学生的信息
     * @param student
     * @return
     */
    @PutMapping("/student/update")
    public R updateStudentInfo( @RequestBody Student student)
    {
        if(studentService.update(student))
            return R.success(ResponseCodeEnum.SUCCESS,MessageEnum.OPERATION_SUCCESS);
        return R.error(ResponseCodeEnum.BAD_REQUEST,MessageEnum.OPERATION_FAILED);
    }

    /**
     * 重置学生密码为基础密码
     * @param studentId
     * @return
     */
    @PutMapping("/student/resetPassword")
    public R resetStudentPassword(@RequestParam String studentId)
    {
        if(studentId.isEmpty())
            return R.error(ResponseCodeEnum.BAD_REQUEST,MessageEnum.PARAMETER_INVALID);
        studentService.resetPassword(studentId);
        return R.success(ResponseCodeEnum.SUCCESS,MessageEnum.OPERATION_SUCCESS);
    }

    /**
     * 修改管理员账号状态0为停用，1为启用
     * @param status
     * @param adminId
     * @return
     */
    @PostMapping("/admin/status")///http://localhost/api/dish/status/0?id=65
    ///http://localhost/api/dish/status/1?admin=6
    public R adminstartOrstop(@RequestParam Integer status,@RequestParam  String adminId){
        if(status==null||adminId==null)
            return R.error(ResponseCodeEnum.BAD_REQUEST,MessageEnum.PARAMETER_INVALID);
        adminService.adminstartOrstop(status,adminId);
        return R.success(ResponseCodeEnum.SUCCESS,MessageEnum.OPERATION_SUCCESS);
    }

    /**
     * 修改老师账号状态0为停用，1为启用
     * @param status
     * @param teacherId
     * @return
     */
    @PostMapping("/teacher/status")
    public R teacherstartOrstop(@RequestParam Integer status,@RequestParam String teacherId)
    {   if(status==null||teacherId==null)
            return R.error(ResponseCodeEnum.BAD_REQUEST,MessageEnum.PARAMETER_INVALID);
        teacherService.teacherstartOrstop(status,teacherId);
        return R.success(ResponseCodeEnum.SUCCESS,MessageEnum.OPERATION_SUCCESS);
    }

    /**
     * 修改学生账号的状态 0为停用，1为启用
     * @param status
     * @param studentId
     * @return
     */
    @PostMapping("/student/status")
    public R studentstartOrstop(@RequestParam Integer status,@RequestParam String studentId)
    {   if(status==null||studentId==null)
        return R.error(ResponseCodeEnum.BAD_REQUEST,MessageEnum.PARAMETER_INVALID);
       studentService.studentstartOrstop(status,studentId);
        return R.success(ResponseCodeEnum.SUCCESS,MessageEnum.OPERATION_SUCCESS);
    }

    /**
     * 管理员账号的分页查询
     * @param adminPageQueryDTO
     * @return
     */
    @GetMapping("/admin/page")
    public R<PageResult> getadminByPage(@RequestParam(defaultValue = "1") int pageNum,
                                        @RequestParam(defaultValue = "10") int pageSize,@RequestBody AdminPageQueryDTO adminPageQueryDTO)
    {
        PageResult pageResult=adminService.pageQuery(pageNum,pageSize,adminPageQueryDTO);
        return R.success(ResponseCodeEnum.SUCCESS,pageResult,MessageEnum.OPERATION_SUCCESS);
    }

    /**
     * 老师账号的分页查询
     * @param teacherPageQueryDTO
     * @return
     */
    @GetMapping("/teacher/page")
    public R<PageResult> getteacherByPage(@RequestParam(defaultValue = "1") int pageNum,
                                          @RequestParam(defaultValue = "10") int pageSize,@RequestBody TeacherPageQueryDTO teacherPageQueryDTO)
    {
        PageResult pageResult=teacherService.pageQuery(pageNum,pageSize,teacherPageQueryDTO);
        return R.success(ResponseCodeEnum.SUCCESS,pageResult,MessageEnum.OPERATION_SUCCESS);
    }

    /**
     * 学生账号的分页查询
     * @param studentPageQueryDTO
     * @return
     */
    @GetMapping("/student/page")
    public R<PageResult> getstudentByPage(@RequestParam(defaultValue = "1") int pageNum,
                                          @RequestParam(defaultValue = "10") int pageSize,@RequestBody StudentPageQueryDTO studentPageQueryDTO)
    {
        PageResult pageResult=studentService.pageQuery(pageNum,pageSize,studentPageQueryDTO);
        return R.success(ResponseCodeEnum.SUCCESS,pageResult,MessageEnum.OPERATION_SUCCESS);
    }


}
